package multi_thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Demo3 {
    //注意前台线程问题，即使主线程以及结束，但还在运行
    //模拟线程池
//    1、核心线程数、最大线程数  管理策略。
//    2、任务队列BlockingQueue
//    3、非核心线程存活时间
//    4、submit方法提交任务
    //如果要添加一个最大线程数
    static class MyThreadPool{//为何这里要为static，静态内部类
        private BlockingQueue<Runnable> queue=new ArrayBlockingQueue<>(1000);
        private int MaxThread;
        private List<Thread> list=new ArrayList<>();
        public MyThreadPool(int n,int MaxThread) {
            this.MaxThread=MaxThread;
            for (int i = 0; i < n; i++) {
               creatThread();
            }
        }
        public void submit(Runnable runnable){
            try {
                if(queue.size()>500&&list.size()<=MaxThread){
                   // while (true){//会无限制创建线程
                       creatThread();
                   // }
                }
                this.queue.put(runnable);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        private void creatThread(){
            Thread t=new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true){//关于while不用if判断问题
                        try {
                            Runnable task=queue.take();
                            task.run();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });
            list.add(t);
            t.start();
        }
    }
    public static void main(String[] args) {
        MyThreadPool myThreadPool=new MyThreadPool(10,30);
        for (int i = 0; i < 100000; i++) {
            int id =i;//变量捕获
            Runnable runnable=new Runnable() {
                @Override
                public void run() {
                    System.out.println(id+" "+Thread.currentThread().getName());
                }
            };
            myThreadPool.submit(runnable);
        }
    }
}
